import type { ConfigEnv, UserConfig } from "vite";
import { loadEnv } from "vite";
import { resolve } from "path";
import { version } from "./package.json";
import dayjs from "dayjs";
import Vue from "@vitejs/plugin-vue";
import VueJsx from "@vitejs/plugin-vue-jsx";
import VueSetupExtend from "vite-plugin-vue-setup-extend";
import ESLint from "vite-plugin-eslint";
import Inspect from "vite-plugin-inspect";
import Legacy from "@vitejs/plugin-legacy";
import Compression from "vite-plugin-compression";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { AntDesignVueResolver, VueUseComponentsResolver } from "unplugin-vue-components/resolvers";
import { AndDesignVueResolve as AndDesignStyleVueResolve, createStyleImportPlugin } from "vite-plugin-style-import";

// https://vitejs.dev/config/
export default ({ command, mode }: ConfigEnv): UserConfig => {
  const envs = formatEnv(mode);
  const isBuild = command === "build";

  envs.VITE_IS_DEBUG && console.time("buildViteConfig");

  const viteConfig: UserConfig = {
    base: "/",
    clearScreen: false,
    resolve: {
      dedupe: ["vue"],
      alias: { "@/": `${resolve(__dirname, "src")}/`, "~/": `${resolve(__dirname, "src")}/` },
      // 忽略后缀名的配置选项, 添加 .vue 选项时要记得原本默认忽略的选项也要手动写入
      extensions: [".mjs", ".js", ".jsx", ".ts", ".tsx", ".json", ".vue"]
    },
    optimizeDeps: {
      include: ["vue"]
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: {
            hack: `true; @import (reference) "${resolve("src/assets/styles/variables.less")}";`,
            "primary-color": "#0033CC",
            "btn-font-size-sm": "12px"
          },
          javascriptEnabled: true
        }
      }
    }
  };

  // 生成环境清理调试信息
  viteConfig.esbuild = {
    drop: isBuild && mode == "production" ? ["console", "debugger"] : []
  };

  // 全局变量
  viteConfig.define = {
    __APP__: JSON.stringify({
      version: version,
      buildTime: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss")
    })
  };

  // 打包配置
  viteConfig.build = {
    target: "es2015",
    sourcemap: isBuild && mode == "development",
    // 打包文件大小警告的限制 https://cn.vitejs.dev/config/#build-chunksizewarninglimit
    chunkSizeWarningLimit: 800,
    // 禁用 gzip 压缩大小报告, 提高大型项目的构建性能
    reportCompressedSize: false,
    // development模式打包使用esbuild
    minify: "esbuild",
    rollupOptions: {
      output: {
        chunkFileNames: `assets/js/[name]-[hash].js`,
        entryFileNames: `assets/js/main-[hash].${version}.js`,
        assetFileNames: chunkInfo => {
          if ((chunkInfo.name + "").includes(".css")) {
            return `assets/css/[name]-[hash].[ext]`;
          }
          return `assets/res/[name]-[hash].[ext]`;
        }
      }
    }
  };

  // 开发服务容器环境配置
  viteConfig.server = {
    host: "0.0.0.0",
    port: envs.VITE_HTTP_PORT
  };

  // 插件配置
  viteConfig.plugins = [
    // 官方VUE模板解析器
    Vue(),
    // [Jsx支持](https://www.npmjs.com/package/@vitejs/plugin-vue-jsx)
    VueJsx(),
    // [script setup use name for SFC](https://github.com/vbenjs/vite-plugin-vue-setup-extend)
    VueSetupExtend(),
    // ESLint
    ESLint({
      include: ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "src/*.ts", "src/*.tsx", "src/*.vue"],
      cache: false,
      lintOnStart: false
    }),
    // 浏览器支持
    Legacy({
      targets: ["> 1%, last 1 version", "not IE 11"] // 注意：VUE3不再支持IE11
    }),
    // https://github.com/antfu/unplugin-auto-import
    AutoImport({
      dts: "types/auto-imports.d.ts",
      dirs: ["src/hooks", "src/store/modules"],
      imports: [
        "vue",
        "vue-router",
        "pinia",
        {
          vue: ["createVNode"],
          "ant-design-vue": [
            "TreeDataItem",
            ["message", "antdMessage"],
            ["notification", "antdNotification"],
            ["Modal", "antdModal"]
          ],
          "@ant-design/icons-vue": ["ExclamationCircleOutlined"]
        }
      ]
    }),

    // https://github.com/antfu/unplugin-vue-components
    Components({
      dirs: ["src/components"],
      extensions: ["vue"],
      include: [/\.vue$/, /\.vue\?vue/, /\.tsx$/],
      dts: "types/components.d.ts",
      resolvers: [AntDesignVueResolver({ resolveIcons: true, importLess: true }), VueUseComponentsResolver()]
    }),

    // https://github.com/vbenjs/vite-plugin-style-import
    createStyleImportPlugin({
      resolves: [AndDesignStyleVueResolve()]
    })

    // createHtmlPlugin({
    //   minify: true,
    //   //在这里写entry后，你将不需要在`index.html`内添加 script 标签，原有标签需要删除
    //   entry: "src/main.ts",
    //   // 如果你想将 `index.html`存放在指定文件夹，可以修改它，否则不需要配置
    //   // template: "public/index.html",
    //   //需要注入 index.html ejs 模版的数据
    //   inject: {
    //     data: {
    //       appName: envs.VITE_APP_NAME
    //     }
    //   }
    // })
  ];

  // 调试插件
  if (envs.VITE_PLUGIN_INSPECT) {
    viteConfig.plugins.push(
      Inspect({
        enabled: true
      })
    );
  }

  // [生产环境资源压缩，结合nginx gzip部署访问丝滑无比](https://github.com/alloc/vite-plugin-compress)
  if (envs.VITE_BUILD_ZIP) {
    viteConfig.plugins.push(Compression());
  }

  envs.VITE_IS_DEBUG && console.timeEnd("buildViteConfig");

  return viteConfig;
};

/**
 * 格式化配置信息
 * @param mode
 */
const formatEnv = (mode: string): ViteEnv => {
  const envs = loadEnv(mode, process.cwd());
  const ret: any = {
    IS_DEBUG: process.argv.includes("--debug")
  };
  process.env["IS_DEBUG"] = ret.IS_DEBUG;
  for (const envName of Object.keys(envs)) {
    let realName = (envs[envName] as any).replace(/\\n/g, "\n");
    if (["true", "false"].includes(realName.toLowerCase())) {
      realName = JSON.parse(realName.toLowerCase());
    }

    if (/^[0-9]*$/.test(realName)) {
      realName = Number(realName);
    }

    ret[envName] = realName;
    process.env[envName] = realName;
  }
  return ret;
};
